<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="头像" :label-width="labelWidth">
        <UploadImg v-model:image-url="form.avatar" :api="uploadAvatar" :file-size="5">
          <template #tip>头像最大为 5M</template>
        </UploadImg>
      </ElFormItem>
      <ElFormItem label="用户名" :label-width="labelWidth" prop="username">
        <ElInput v-model="form.username" />
      </ElFormItem>
      <ElFormItem label="昵称" :label-width="labelWidth" prop="nickname">
        <ElInput v-model="form.nickname" />
      </ElFormItem>
      <ElFormItem label="密码" :label-width="labelWidth" prop="password">
        <ElInput v-model="form.password" type="password" autocomplete="off" />
      </ElFormItem>
      <ElFormItem label="所属部门" :label-width="labelWidth" prop="deptId">
        <ElTreeSelect
          key="id"
          v-model="form.deptId"
          :data="deptTree"
          :render-after-expand="false"
          :props="deptTreeProps"
          check-strictly />
      </ElFormItem>
      <ElFormItem label="所属区域" :label-width="labelWidth" prop="areaId">
        <ElTreeSelect v-model="form.areaId" :data="areas" :render-after-expand="false" :props="areaTreeProps" key="id" />
      </ElFormItem>
      <ElFormItem label="手机号" :label-width="labelWidth" prop="phone">
        <ElInput v-model="form.phone" />
      </ElFormItem>
      <ElFormItem label="邮箱" :label-width="labelWidth" prop="email">
        <ElInput v-model="form.email" />
      </ElFormItem>
      <ElFormItem label="角色" :label-width="labelWidth" prop="roleId">
        <ElSelect v-model="form.roleId">
          <ElOption v-for="item in roles" :key="item.value" :label="item.label" :value="item.value" />
        </ElSelect>
      </ElFormItem>
      <!-- <ElFormItem label="岗位" :label-width="labelWidth" prop="postIds">
        <ElTreeSelect
          multiple
          v-model="row.postIds"
          :data="posts"
          :render-after-expand="false"
          :props="postTreeProps"
          key="id" />
      </ElFormItem> -->
      <ElFormItem label="用户类别" :label-width="labelWidth" prop="type">
        <ElSelect v-model="form.type" :default-first-option="true">
          <ElOption v-for="item in userTypes" :key="item.value" :label="item.label" :value="item.value" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="分组" :label-width="labelWidth" prop="groupIds">
        <ElTreeSelect multiple v-model="form.groupIds" :data="groups" :render-after-expand="false" :props="groupProps" key="id" />
      </ElFormItem>
      <ElFormItem label="锁定状态" :label-width="labelWidth" prop="lockFlag">
        <ElRadioGroup v-model="form.lockFlag" id="lockFlag">
          <ElRadio label="0" border>有效</ElRadio>
          <ElRadio label="1" border>锁定</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, ElTreeSelect, ElSelect, ElOption, FormInstance } from 'element-plus'
import { addUser, updateUser, userExist } from '@api/uc/user'
import { getUser } from '@api/uc/user'
import { uiUpload } from '@api/upload'
import { listRoleOption } from '@api/uc/role'
import { getAllDeptTree, TreeNode } from '@/utils/param'
import { User } from '@api/uc/user/interface'
import { FormType } from '@/enums'
import { SelectOption } from '@/api/interface'
import { encrypt } from '@/utils/aes'
import UploadImg from '@/components/Upload/Img.vue'
import { listDictByType } from '@api/uc/dict'
const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<User.Form>>({})
const deptTree = ref<TreeNode[]>([])
const roles = ref<SelectOption[]>([])
const userTypes = ref<SelectOption[]>([])
const areas = ref([])
const groups = ref([])

onMounted(async () => {
  // 部门树
  deptTree.value = await getAllDeptTree()
  // 角色选项
  roleOptions()
  // 用户类别
  getUserTypes()
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

// 部门树
const roleOptions = () => {
  listRoleOption().then(resp => {
    const { data } = resp
    roles.value = data
  })
}
// 部门树
const getUserTypes = () => {
  listDictByType('user_type').then(resp => {
    const { data } = resp
    userTypes.value = data
  })
}

const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const reg = /^[1][3-9][0-9]{9}$/
  if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

const validateUsername = (rule: any, value: any, callback: any) => {
  userExist(value, form.value?.id).then(resp => {
    if (!value) {
      return callback()
    }
    if (resp.data) {
      callback(new Error('该用户已存在'))
    } else {
      callback()
    }
  })
}

// 邮箱校验
const validateEmail = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const emailRegExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
  const emailRegExp1 = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
  if ((!emailRegExp.test(value) && value != '') || !emailRegExp1.test(value)) {
    callback(new Error('请输入有效邮箱格式！'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { max: 64, message: '用户名称最大64个字符', trigger: 'blur' },
    { validator: validateUsername, trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { max: 64, message: '昵称最大64个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { max: 20, message: '密码最大20个字符', trigger: 'blur' }
  ],
  phone: [
    { max: 20, message: '手机号最大20个字符', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { max: 100, message: '邮箱最多100个字符', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  // areaId: [{ required: true, message: '请选择区域', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  type: [{ required: true, message: '请选择用户类别', trigger: 'blur' }]
  // postIds: [{ required: true, message: '请选择岗位', trigger: 'blur' }],
  // groupIds: [{ required: true, message: '请选择分组', trigger: 'blur' }]
})

// const avatarUrl = ref<string | undefined>(void 0)

const deptTreeProps = {
  value: 'id',
  label: 'name',
  children: 'children'
}

const areaTreeProps = {
  label: (data: any) => data.name,
  children: 'children',
  value: 'id'
}

// const roleProps = {
//   label: (data: any, node: any) => data.name,
//   children: 'children',
//   value: 'id'
// }

// const postProps = {
//   label: (data: any, node: any) => data.name,
//   children: 'children',
//   value: 'id'
// }
const groupProps = {
  label: (data: any) => data.name,
  children: 'children',
  value: 'id'
}

const open = async (type: FormType, id?: string) => {
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
    rules.password = [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { max: 20, message: '密码最大20个字符', trigger: 'blur' }
    ]
    form.value = { lockFlag: '0' }
  } else {
    rules.password = undefined
    try {
      const { data } = await getUser(id!)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
}
// 上传头像
function uploadAvatar(formData: FormData) {
  return uiUpload('avatar', formData)
}
const onSaveClicked = () => {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const user = { ...unref(form) }
    if (formType.value === FormType.ADD) {
      user.password = encrypt(user.password!)
      addUser(user).then(() => {
        sendSuccess()
        close()
      })
    } else if (formType.value === FormType.EDIT) {
      if (user.password) {
        user.password = encrypt(user.password!)
      }
      updateUser(user).then(() => {
        sendSuccess()
        close()
      })
    }
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
